package com.jsh.erp.service.print;

import com.jsh.erp.datasource.entities.DepotHead;
import com.jsh.erp.datasource.entities.DepotItemVo4WithInfoEx;
import com.jsh.erp.datasource.entities.Supplier;
import com.jsh.erp.service.depotHead.DepotHeadService;
import com.jsh.erp.service.depotItem.DepotItemService;
import com.jsh.erp.service.organization.OrganizationService;
import com.jsh.erp.service.person.PersonService;
import com.jsh.erp.service.supplier.SupplierService;
import com.jsh.erp.utils.StringUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
public class PrintService {

    @Resource
    private DepotHeadService depotHeadService;
    @Resource
    private DepotItemService depotItemService;
    @Resource
    private OrganizationService organizationService;
    @Resource
    private SupplierService supplierService;
    @Resource
    private PersonService personService;


    private String printPdfForEntities(DepotHead depotHead, Supplier supplier, List<DepotItemVo4WithInfoEx> detailList,String template,int count) throws Exception {
        ClassLoader classLoader = PrintService.class.getClassLoader();
        InputStream inputStream_p = classLoader
                .getResourceAsStream("templates/parent.html");
        String TemplateHtmlBody = IOUtils.toString(inputStream_p, StandardCharsets.UTF_8);
        inputStream_p.close();
        InputStream inputStream_book = classLoader
                .getResourceAsStream("templates/cn/"+template);
        String bookHtml = IOUtils.toString(inputStream_book, StandardCharsets.UTF_8);
        inputStream_book.close();
        StringBuilder htmlBuilder = new StringBuilder();
        int index=0;
        int pages = detailList.size()/count+(detailList.size()%count>0?1:0);
        while(index<pages-1){
            String tbody = "";
            int sum = 0;
            BigDecimal total = new BigDecimal(0);
            for(int i=0;i<count;i++){
                tbody+="<tr>";
                tbody+="<td>"+(i+1)+"</td>";
                tbody+="<td>"+detailList.get(i+index*count).getMName()+"</td>";
                tbody+="<td>"+detailList.get(i+index*count).getMModel()+"</td>";
                tbody+="<td>"+detailList.get(i+index*count).getMunit()+"</td>";
                tbody+="<td>"+detailList.get(i+index*count).getOpernumber().intValue()+"</td>";
                sum+=detailList.get(i+index*count).getOpernumber().intValue();
                tbody+="<td>"+detailList.get(i+index*count).getUnitprice().setScale(2,   BigDecimal.ROUND_HALF_UP)+"</td>";
                BigDecimal totalPrice = detailList.get(i+index*count).getUnitprice().multiply(detailList.get(i+index*count).getOpernumber()).setScale(2,   BigDecimal.ROUND_HALF_UP);
                total = total.add(totalPrice);
                tbody+="<td>"+ totalPrice +"</td>";
                tbody+="</tr>";
            }
            index++;
            htmlBuilder.append(parseToBookTemplate(depotHead,supplier, bookHtml, index, tbody,sum,total));
        }
        String tbody = "";
        int sum = 0;
        BigDecimal total = new BigDecimal(0);
        for(int i=0;i<detailList.size()-index*count;i++){
            tbody+="<tr>";
            tbody+="<td>"+(i+1)+"</td>";
            tbody+="<td>"+detailList.get(i+index*count).getMName()+"</td>";
            tbody+="<td>"+detailList.get(i+index*count).getMModel()+"</td>";
            tbody+="<td>"+detailList.get(i+index*count).getMunit()+"</td>";
            tbody+="<td>"+detailList.get(i+index*count).getOpernumber().intValue()+"</td>";
            sum+=detailList.get(i+index*count).getOpernumber().intValue();
            tbody+="<td>"+detailList.get(i+index*count).getUnitprice().setScale(2,   BigDecimal.ROUND_HALF_UP)+"</td>";
            BigDecimal totalPrice = detailList.get(i+index*count).getUnitprice().multiply(detailList.get(i+index*count).getOpernumber()).setScale(2,   BigDecimal.ROUND_HALF_UP);
            total = total.add(totalPrice);
            tbody+="<td>"+ totalPrice +"</td>";
            tbody+="</tr>";
        }
        htmlBuilder.append(parseToBookTemplate(depotHead,supplier, bookHtml, ++index, tbody, sum, total));
        TemplateHtmlBody = TemplateHtmlBody.replace("{{CONTENT}}", htmlBuilder.toString());
        return  TemplateHtmlBody;
    }

    private String parseToBookTemplate(DepotHead depotHead, Supplier supplier, String bookHtml, int index, String tbody, int sum, BigDecimal total) throws Exception {
        String salesman = StringUtils.defaultString(depotHead.getSalesman()).replace("<", "").replace(">", "");
        bookHtml = StringUtils.replace(bookHtml, "{{KEHU}}", StringUtils.defaultString(supplier.getSupplier()));
        bookHtml = StringUtils.replace(bookHtml, "{{GONGCHENG}}", StringUtils.defaultString(depotHead.getRemark()));
        bookHtml = StringUtils.replace(bookHtml, "{{BEIZHU}}", StringUtils.defaultString(depotHead.getRemark()));
        bookHtml = StringUtils.replace(bookHtml, "{{GUANLIANDINGDAN}}", StringUtils.defaultString(depotHead.getLinknumber()));
        bookHtml = StringUtils.replace(bookHtml, "{{RIQI}}", StringUtils.defaultString(DateUtils.formatDate(depotHead.getOpertime(),"yyyy-MM-dd")));
        bookHtml = StringUtils.replace(bookHtml, "{{BIANHAO}}", StringUtils.defaultString(depotHead.getNumber())+(index<10?("0"+index):index));
        bookHtml = StringUtils.replace(bookHtml, "{{ZHIDAN}}", StringUtils.defaultString(depotHead.getOperpersonname()));
        bookHtml = StringUtils.replace(bookHtml, "{{XIAOSHOU}}", StringUtil.isEmpty(salesman)?"":this.personService.getPersonByIds(salesman));
        bookHtml = StringUtils.replace(bookHtml, "{{TBODY}}", StringUtils.defaultString(tbody));
        bookHtml = StringUtils.replace(bookHtml, "{{SHULIANG}}", sum+"");
        bookHtml = StringUtils.replace(bookHtml, "{{JINE}}", total.setScale(2,   BigDecimal.ROUND_HALF_UP).toString());
        return bookHtml;
    }

    public String salesOrder(long depotHeadID) throws Exception {
        DepotHead depotHead = this.depotHeadService.getDepotHead(depotHeadID);
        Supplier supplier = this.supplierService.getSupplier(depotHead.getOrganid());
        List<DepotItemVo4WithInfoEx> detailList = this.depotItemService.getDetailList(depotHeadID);
        return printPdfForEntities(depotHead,supplier,detailList,"salesOrders.html",1000);
    }

    public String printSalesOut(long depotHeadID) throws Exception {
        DepotHead depotHead = this.depotHeadService.getDepotHead(depotHeadID);
        Supplier supplier = this.supplierService.getSupplier(depotHead.getOrganid());
        List<DepotItemVo4WithInfoEx> detailList = this.depotItemService.getDetailList(depotHeadID);
        return printPdfForEntities(depotHead,supplier,detailList,"salesOut.html",14);
    }

    public String printPurchaseOrders(long depotHeadID) throws Exception {
        DepotHead depotHead = this.depotHeadService.getDepotHead(depotHeadID);
        Supplier supplier = this.supplierService.getSupplier(depotHead.getOrganid());
        List<DepotItemVo4WithInfoEx> detailList = this.depotItemService.getDetailList(depotHeadID);
        return printPdfForEntities(depotHead,supplier,detailList,"purchaseOrders.html",1000);
    }

    public String purchaseIn(long depotHeadID) throws Exception {
        DepotHead depotHead = this.depotHeadService.getDepotHead(depotHeadID);
        Supplier supplier = this.supplierService.getSupplier(depotHead.getOrganid());
        List<DepotItemVo4WithInfoEx> detailList = this.depotItemService.getDetailList(depotHeadID);
        return printPdfForEntities(depotHead,supplier,detailList,"purchaseIn.html",15);
    }
}
